package com.farina.cryptobox;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import com.farina.cryptobox.R;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class Change_Password extends Activity {

	private String usn="";
	private String key="";
	public final static String EXTRA_MESSAGE_NEWPWD = "com.example.myfirstapp.NEWPWD";
	static final int DIALOG_CONFIRM_ID = 1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent intent = getIntent();
		String usn = intent.getStringExtra(AccountManager.EXTRA_MESSAGE_USN2);
		String key = intent.getStringExtra(AccountManager.EXTRA_MESSAGE_PPH);
		this.usn=usn;
		this.key=key;
		setContentView(R.layout.activity_change__password);
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_change__password, menu);
		return true;
	}
	
	@Override
    protected void onStop() {
        super.onStop();
        this.finish();
    }
	
	@Override
    protected void onPause() {
        super.onStop();
        this.finish();
    }
	


	public void changePwdReal() throws NoSuchAlgorithmException, UnsupportedEncodingException{

		EditText pwdText = (EditText) findViewById(R.id.newPwdField);
		String pwd =pwdText.getText().toString();
		String ph=CryptoFunction.MD5(pwd);
		pwd=CryptoFunction.SHA256(pwd)+"\n";

		
		changePwdAccount(usn, pwd);
		Intent intent = new Intent(this, AccountManager.class);
    	intent.putExtra(EXTRA_MESSAGE_NEWPWD, ph);
    	setResult(RESULT_OK,intent);
    	this.finish();
		
	}
	
	public void changePwd(View view) throws NoSuchAlgorithmException, UnsupportedEncodingException{
		EditText oldpwdText = (EditText) findViewById(R.id.oldPwdField);
		String oldkey = CryptoFunction.MD5(oldpwdText.getText().toString());
		EditText pwdText = (EditText) findViewById(R.id.newPwdField);
		String pwd =pwdText.getText().toString();
		EditText pwdReText = (EditText) findViewById(R.id.retypePwdField);
		String pwdRe = pwdReText.getText().toString();


		if(!oldkey.equals(key)){
			TextView oldpwdLabel=(TextView) findViewById(R.id.oldPwdLabel);
			oldpwdLabel.setText("Wrong Password");
			oldpwdLabel.setTextColor(Color.RED);
			oldpwdText.setText("");
			return;
		}

		if(pwd.length()<2){
			TextView pwdLabel=(TextView) findViewById(R.id.newPwdLabel);
			pwdLabel.setText("Too Short Password! (almost 8 char)");
			pwdLabel.setTextColor(Color.RED);
			return;
		}

		if(!pwdRe.equals(pwd)) {
			TextView retpwdLabel=(TextView) findViewById(R.id.retPwdLabel);
			retpwdLabel.setText("Please Retype the Password");
			retpwdLabel.setTextColor(Color.RED);
			pwdReText.setText("");
			return;
		}
		
		if(!checkAccount(usn)){
			return;
		}
		
		this.showDialog(DIALOG_CONFIRM_ID);
	}
	
	protected Dialog onCreateDialog(int id) {
		Dialog dialog=null;
		switch(id) {
		case DIALOG_CONFIRM_ID:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Are you sure you want change the account password?")
			.setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					try {
						changePwdReal();
					} catch (NoSuchAlgorithmException e) {
						e.printStackTrace();
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			dialog = builder.create();
			break;
		default:
			dialog = null;
		}
		return dialog;
	}

	public void changePwdAccount(String usn, String pwd){

		File f = new File(getExternalFilesDir(null), "accounts.txt");
		String fileToS="";
		FileReader fr = null;
		BufferedReader br = null;
		try {
			usn=CryptoFunction.MD5(usn);
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		try{
			fr = new FileReader(f);
			br = new BufferedReader(fr);
			while(true){
				String tmpUsn = br.readLine();
				if(tmpUsn==null)break;
				fileToS=fileToS+tmpUsn+"\n";
				if(tmpUsn.equals(usn)){fileToS=fileToS+pwd; br.readLine(); continue;}
				String tmpPwd = br.readLine();
				fileToS=fileToS+tmpPwd+"\n";
			}			
			br.close(); 
		}
		catch (IOException e) {      
			e.printStackTrace(); 
		}

		writFileString(f, fileToS);

	}

	public void writFileString(File f, String s){
		FileWriter fw = null;
		BufferedWriter bw = null;
		try{
			fw = new FileWriter(f, false);
			bw = new BufferedWriter(fw);
			bw.write(s);
			bw.close();
		}
		catch (IOException e) {      
			e.printStackTrace(); 
		}

	}

	public boolean checkAccount(String usn){
		File f = new File(getExternalFilesDir(null), "accounts.txt");
		FileReader fr = null;
		BufferedReader br = null;
		try {
			usn=CryptoFunction.MD5(usn);
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		try{
			fr = new FileReader(f);
			br = new BufferedReader(fr);
			while(true){
				String tmpUsn = br.readLine();
				if(tmpUsn==null){br.close(); return false;}
				br.readLine();
				if(tmpUsn.equals(usn))break;
			}

			br.close(); 
		}
		catch (IOException e) {      
			e.printStackTrace(); 
		}

		return true;
	}

	public void close(View view) {
		this.finish();
	}

}
